﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
namespace BYManageInfoSystem
{
    public partial class Frm_DepMonthTTRecvAndPay : Form
    {
        private DGBY.BLL.BYDepartTab m_bllBYDepartTab = new DGBY.BLL.BYDepartTab();
        private DGBY.BLL.FeeTTLoanAndFeeRegDetailInfoTab m_bllFeeTTLoanAndFeeRegDetailInfoTab = new DGBY.BLL.FeeTTLoanAndFeeRegDetailInfoTab();
        private DGBY.BLL.FeeTTMonthRecvAndPayTab m_bllFeeTTMonthRecvAndPayTab = new DGBY.BLL.FeeTTMonthRecvAndPayTab();
        UltraGridColumn ultraGridColumn1 = null;
        private int m_nSelectFeeTTMonthRecvAndPayTabID = 0;
        Dictionary<string, List<int>> dicFacName2DetailInfoTabIDList = new Dictionary<string, List<int>>();
        public class CustomMergedCellEvaluator : Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
        {
           
            // 合并日期相同的单元格（无需时间精确相同）
            public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2, UltraGridColumn column)
            {
                string str1 = (string)row1.GetCellValue(column);
                string str2 = (string)row2.GetCellValue(column);
                return str1 == str2;

            }

        }
        private bool IsDecimal(string strInput)
        {
            bool bRet = Regex.IsMatch(strInput, @"([1-9]+[0-9]*(\.[0-9]+))|(0(\.[0-9]+))");
            return bRet;
        }

        private bool IsNum(string strInput)
        {
            bool bRet = Regex.IsMatch(strInput, @"^[1-9]+\d*$");
            return bRet;
        }

        private bool ValidDate(string strInput)
        {
            if (strInput.Length != 8)
                return false;
            else
                return IsNum(strInput);
        }

        public bool IsDecimal(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else if (!IsDecimal(TextBox.Text) && !IsNum(TextBox.Text))
            {
                errorProvider1.SetError(TextBox, "必须输入数字");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }

        public bool IsNum(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else if (!IsNum(TextBox.Text))
            {
                errorProvider1.SetError(TextBox, "必须输入数字");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }

        public bool IsNull(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }
        public Frm_DepMonthTTRecvAndPay()
        {
            InitializeComponent();
        }
        public void InitUltraWinGridSetting()
        {
            this.ultraGrid1.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorNumberStyle = Infragistics.Win.UltraWinGrid.RowSelectorNumberStyle.VisibleIndex;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorWidth = 40;

        }

        public void LocalPrintPreveiw()
        {
            Infragistics.Shared.ResourceCustomizer rc = Infragistics.Win.Printing.Resources.Customizer;//Resources.Customizer;
            rc.SetCustomizedString("PrintPreview_DialogCaption", "打印预览");
            rc.SetCustomizedString("PrintPreview_Tool_Print", "打印(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_ClosePreview", "关闭(&C)");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuPreviewZoom", "显示比例");
            rc.SetCustomizedString("PrintPreview_Tool_Current_Page", "当前页");
            rc.SetCustomizedString("PrintPreview_Tool_Exit", "退出(&X)");
            rc.SetCustomizedString("PrintPreview_Tool_First_Page", "第一页");
            rc.SetCustomizedString("PrintPreview_Tool_Go_To", "跳至");
            rc.SetCustomizedString("PrintPreview_Tool_Last_Page", "最后一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_Page", "下一页");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_Page", "前一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_View", "下一视图(&N)");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_View", "前一视图(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_Hand_Tool", "手型工具(&H)");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Setup", "页面设置(&U)");
            rc.SetCustomizedString("PrintPreview_Tool_Snapshot_Tool", "快照工具(&S)");
            rc.SetCustomizedString("PrintPreview_Tool_View", "视图(&V)");
            rc.SetCustomizedString("PrintPreview_Tool_Whole_Page", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom", "缩放(&Z)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In", "放大");

            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out", "缩小");

            rc.SetCustomizedString("PrintPreview_ToolCategory_Context_Menus", "上下文菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_File", "文件");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Menus", "菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Tools", "工具栏");
            rc.SetCustomizedString("PrintPreview_ToolCategory_View", "视图");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Zoom_Mode", "缩放模式");

            rc.SetCustomizedString("PrintPreview_ToolTip_ClosePreview", "关闭");
            rc.SetCustomizedString("PrintPreview_ToolTip_Zoom", "缩放");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "页:{0}/{1}");

            rc.SetCustomizedString("CustomizeImg_ToolBar_MenuBar", "菜单");
            rc.SetCustomizedString("CustomizeImg_ToolBar_Standard", "标准");
            rc.SetCustomizedString("CustomizeImg_ToolBar_View", "视图");
            rc.SetCustomizedString("PrintPreview_Tool_File", "文件(&F)");
            rc.SetCustomizedString("PrintPreview_Tool_Tools", "工具(&T)");
            rc.SetCustomizedString("PrintPreview_Tool_Dynamic_Zoom_Tool", "动态缩放工具(&D)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out_Tool", "缩小工具");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In_Tool", "放大工具");
            // rc.SetCustomizedString("PrintPreview_Tool_Page_Layout","菜单");
            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PreviewRowColSelection_SelectedPages", "{0} x {1} 页");

            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Width", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_MarginWidth", "文字宽度");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_PageWidth", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_WholePage", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Layout", "页面布局");
            rc.SetCustomizedString("PrintPreview_Tool_Margin_Width", "文字宽度");
            rc.SetCustomizedString("ContextMenuPreviewHand", "缩放视图");


            rc.SetCustomizedString("PrintPreview_Tool_Reduce_Page_Thumbnails", "缩小");
            rc.SetCustomizedString("PrintPreview_Tool_Show_Page_Numbers", "显示页号");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuThumbnail", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Enlarge_Page_Thumbnails", "放大");
            rc.SetCustomizedString("PrintPreview_Tool_Thumbnails", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Continuous", "连续排序");
            //说明
            rc.SetCustomizedString("StatusBar_DynamicZoom_Instructions", "单击并拖动进行缩放操作");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "当前页: {0} / {1}");
            rc.SetCustomizedString("StatusBar_SnapShot_Instructions", "单击并拖动,系统将选定矩型区域复制到剪帖板");
            rc.SetCustomizedString("StatusBar_ZoomIn_Instructions", "单击并拖动,系统将放大选定矩型区域");
            rc.SetCustomizedString("StatusBar_ZoomOut_Instructions", "单击并拖动,系统将缩小选定矩型区域");
            rc.SetCustomizedString("StatusBar_Hand_Instructions", "单击并拖动以便显示更多内容");
        }
        private void InitCombox()
        {
            DataSet ds = m_bllBYDepartTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBoxDep.DataSource = ds.Tables[0];
                this.comboBoxDep.DisplayMember = "部门名称";
                this.comboBoxDep.ValueMember = "BYDepartTabID";
                this.comboBoxDep.SelectedIndex = 0;
            }
        }
        private void Frm_DepMonthTTRecvAndPay_Load(object sender, EventArgs e)
        {
            InitCombox();
            LocalPrintPreveiw();
            InitUltraWinGridSetting();
        }
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        private void ImportRecord()
        {
            dicFacName2DetailInfoTabIDList.Clear();
            DateTime dtFirst = FirstDayOfMonth(this.dateTimePickerDate.Value);
            DateTime dtEnd = LastDayOfMonth(this.dateTimePickerDate.Value);
            DataSet ds = m_bllFeeTTLoanAndFeeRegDetailInfoTab.GetTTMonthIncomeInfoList(@"BYDepartTab.DepartName = '" + this.comboBoxDep.Text + "'"
                                     + " and FeeTTLoanAndFeeRegDetailInfoTab.RecvMoneyDate >= '" + dtFirst.Date + "'"
                                     + " and FeeTTLoanAndFeeRegDetailInfoTab.RecvMoneyDate <= '" + dtEnd.Date + "'");

            DataSet ds2 = m_bllFeeTTMonthRecvAndPayTab.GetList(@"FeeTTMonthRecvAndPayTab.BYDepartTabID = '" + this.comboBoxDep.SelectedValue + "'"
                                                + " and FeeTTMonthRecvAndPayTab.TongJiDate >= '" + dtFirst.Date + "'"
                                                + " and FeeTTMonthRecvAndPayTab.TongJiDate <= '" + dtEnd.Date + "'");

            Decimal dtCaiWu = 0;
            Decimal dtOther = 0;
            string strCaiWu = "";
            string strOther = "";
            if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
            {
                dtCaiWu = Convert.ToDecimal(ds2.Tables[0].Rows[0]["财务实付款金额"].ToString());
                dtOther = Convert.ToDecimal(ds2.Tables[0].Rows[0]["其他费用款"].ToString());
                strCaiWu = ds2.Tables[0].Rows[0]["财务备注"].ToString();
                strOther = ds2.Tables[0].Rows[0]["其他备注"].ToString();
                m_nSelectFeeTTMonthRecvAndPayTabID = Convert.ToInt32(ds2.Tables[0].Rows[0]["FeeTTMonthRecvAndPayTabID"].ToString(), 10);
            }
            else
            {
                DGBY.Model.FeeTTMonthRecvAndPayTab modelFeeTTMonthRecvAndPayTab = new DGBY.Model.FeeTTMonthRecvAndPayTab();
                modelFeeTTMonthRecvAndPayTab.TongJiDate = dtFirst.Date;
                modelFeeTTMonthRecvAndPayTab.BYDepartTabID = Convert.ToInt32(this.comboBoxDep.SelectedValue.ToString(), 10);
                m_nSelectFeeTTMonthRecvAndPayTabID = m_bllFeeTTMonthRecvAndPayTab.Add(modelFeeTTMonthRecvAndPayTab);

            }

            DataTable dtNew = new DataTable();

            dtNew.Columns.Add("收支", System.Type.GetType("System.String"));
            dtNew.Columns.Add("名称", System.Type.GetType("System.String"));
            dtNew.Columns.Add("金额", System.Type.GetType("System.Decimal"));
            dtNew.Columns.Add("备注", System.Type.GetType("System.String"));

            ultraGrid1.DataSource = dtNew;

            //foreach (UltraGridColumn column2 in this.ultraGrid1.DisplayLayout.Bands[0].Columns)
            //{
            //    string str = column2.Header.Caption;
            //    if (str == "收支" || str == "名称")
            //    {
            //        column2.RowLayoutColumnInfo.OriginY = 2;
            //    }
            //    else
            //    {
            //        column2.RowLayoutColumnInfo.SpanY = 4;
            //    }

            //}

            DataRow objRow;

            objRow = dtNew.NewRow();

            objRow[0] = "支出";
            objRow[1] = "财务实付款";
            objRow[2] = dtCaiWu;
            objRow[3] = strCaiWu;
            dtNew.Rows.Add(objRow);

            objRow = dtNew.NewRow();

            objRow[0] = "支出";
            objRow[1] = "其他费用款";
            objRow[2] = dtOther;
            objRow[3] = strOther;
            dtNew.Rows.Add(objRow);

            objRow = dtNew.NewRow();

            objRow[0] = "支出";
            objRow[1] = "支出合计";
            objRow[2] = dtCaiWu + dtOther;
            objRow[3] = "";
            dtNew.Rows.Add(objRow);

            //ultraGridColumn1 = ultraGrid1.DisplayLayout.Bands[0].Columns.Add("项目", "项目");
            //ultraGridColumn1.CellActivation = Activation.Disabled;
            //ultraGridColumn1.SortIndicator = SortIndicator.Disabled;
            //ultraGridColumn1.RowLayoutColumnInfo.PreferredCellSize = new Size(1, 1);
            //ultraGridColumn1.RowLayoutColumnInfo.AllowLabelSizing = RowLayoutSizing.None;
            //ultraGridColumn1.RowLayoutColumnInfo.LabelPosition = LabelPosition.LabelOnly;
            //ultraGridColumn1.RowLayoutColumnInfo.OriginX = 0;//有2个列隐藏了
            //ultraGridColumn1.RowLayoutColumnInfo.OriginY = 0;
            //ultraGridColumn1.RowLayoutColumnInfo.SpanX = 4;
            //ultraGridColumn1.RowLayoutColumnInfo.SpanY = 2;
            Decimal dtTotalTemp = 0;
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                string strFacName = ds.Tables[0].Rows[i]["工厂名称"].ToString();
                int nId = Convert.ToInt32(ds.Tables[0].Rows[i]["FeeTTLoanAndFeeRegDetailInfoTabID"].ToString());
                
                if(dicFacName2DetailInfoTabIDList.Keys.Contains(strFacName))
                {
                    List<int> lst = dicFacName2DetailInfoTabIDList[strFacName];
                    lst.Add(nId);
                }
                else
                {
                    List<int> lst = new List<int>();
                    lst.Add(nId);
                    dicFacName2DetailInfoTabIDList.Add(strFacName, lst);
                }
                Decimal dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[i]["实收款合计"].ToString());
                dtTotalTemp += dtTemp;
                bool bFind = false;
                for (int nIndex = 0; nIndex < dtNew.Rows.Count; nIndex++)
                {
                    string strFacNameTemp = dtNew.Rows[nIndex]["名称"].ToString();
                    if (strFacNameTemp.CompareTo(strFacName) == 0)
                    {
                        dtNew.Rows[nIndex]["金额"] = dtTemp + (Decimal)dtNew.Rows[nIndex]["金额"];
                        bFind = true;
                        break;
                    }
                }
                if (!bFind)
                {
                    objRow = dtNew.NewRow();

                    objRow[0] = "收入";
                    dtNew.Rows.Add(objRow);
                    objRow[1] = strFacName;
                    objRow[2] = dtTemp;
                    objRow[3] = ds.Tables[0].Rows[i]["备注"].ToString();
                }

            }

            objRow = dtNew.NewRow();

            objRow[0] = "收入";
            objRow[1] = "收入合计";
            objRow[2] = dtTotalTemp;
            objRow[3] = "";

            dtNew.Rows.Add(objRow);
            //利润
            objRow = dtNew.NewRow();

            objRow[0] = "利润";
            objRow[1] = "";
            objRow[2] = dtTotalTemp - (dtCaiWu + dtOther);
            objRow[3] = "";

            dtNew.Rows.Add(objRow);
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            ImportRecord();
        }

        private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            ultraGrid1.DisplayLayout.Bands[0].UseRowLayout = true;
            ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextVAlign = VAlign.Middle;

            ultraGrid1.DisplayLayout.Bands[0].Columns["收支"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["收支"].MergedCellEvaluator = new
   CustomMergedCellEvaluator();
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {

            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {

            string strTemp = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["收支"].Text;
            if(strTemp == "利润")
                return;

            strTemp = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["名称"].Text;
            if (strTemp == "支出合计" || strTemp == "收入合计")
                return;
            this.textBoxItem.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["名称"].Text;
            this.textBoxJinE.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["金额"].Text;
            this.textBoxNote.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["备注"].Text;
            if (strTemp != "财务实付款" && strTemp != "其他费用款")
                this.textBoxJinE.Enabled = false;

        }

        private void buttonModify_Click(object sender, EventArgs e)
        {
            try
            {
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxJinE))
                    return;
                string strTemp = this.textBoxItem.Text;
                if (strTemp != "财务实付款" && strTemp != "其他费用款")
                {

                }
                else
                {
                    DGBY.Model.FeeTTMonthRecvAndPayTab modelFeeTTMonthRecvAndPayTab = m_bllFeeTTMonthRecvAndPayTab.GetModel(m_nSelectFeeTTMonthRecvAndPayTabID);
                    if (strTemp == "财务实付款")
                    {
                        modelFeeTTMonthRecvAndPayTab.PayMoneyFee = Convert.ToDecimal(this.textBoxJinE.Text);
                        modelFeeTTMonthRecvAndPayTab.PayMoneyFeeNote = this.textBoxNote.Text;
                    }
                    else
                    {
                        modelFeeTTMonthRecvAndPayTab.PayMoneyOtherFee = Convert.ToDecimal(this.textBoxJinE.Text);
                        modelFeeTTMonthRecvAndPayTab.PayMoneyOtherFeeNote = this.textBoxNote.Text;
                    }

                    m_bllFeeTTMonthRecvAndPayTab.Update(modelFeeTTMonthRecvAndPayTab);
                }


                foreach (string strTemp2 in dicFacName2DetailInfoTabIDList.Keys)
                {
                    if (strTemp2.CompareTo(strTemp) == 0)
                    {
                        List<int> lst = dicFacName2DetailInfoTabIDList[strTemp2];
                        foreach (int nId in lst)
                        {
                            DGBY.Model.FeeTTLoanAndFeeRegDetailInfoTab modelFeeTTLoanAndFeeRegDetailInfoTab
                                        = m_bllFeeTTLoanAndFeeRegDetailInfoTab.GetModel(nId);
                            modelFeeTTLoanAndFeeRegDetailInfoTab.Note = this.textBoxNote.Text;
                            m_bllFeeTTLoanAndFeeRegDetailInfoTab.Update(modelFeeTTLoanAndFeeRegDetailInfoTab);
                        }
                        break;
                    }
                }

                ImportRecord();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
          
        }

        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
            // Get the cell being exporter
            UltraGridCell cell = e.GridRow.Cells[e.GridColumn];

            // Get the Merged cells. 
            UltraGridCell[] mergedCells = cell.GetMergedCells();


            // Check to see if there are any merged cells. If not, we don't need to do anything. 
            if (mergedCells != null)
            {
                // There are merged cells. Check to see if the cell being exported is the first one. 
                bool isFirstCell = true;
                foreach (UltraGridCell mergedCell in mergedCells)
                {
                    if (cell.Row.Index > mergedCell.Row.Index)
                    {
                        // If the cell being exported has a higher index that any of the cells
                        // it is merged with, them it's not the first cell and we should already
                        // have handled the merge. 
                        isFirstCell = false;
                        break;
                    }
                }

                // If it is the first cell, merge this cell with the cells below it based on the 
                // count of the merged cells. 
                if (isFirstCell)
                {
                    int rowIndex = e.CurrentRowIndex;
                    int colIndex = e.CurrentColumnIndex;
                    Infragistics.Excel.WorksheetMergedCellsRegion mergedRegion = e.CurrentWorksheet.MergedCellsRegions.Add(
                        rowIndex,
                        colIndex,
                        rowIndex + (mergedCells.Length - 1),
                        colIndex);
                    mergedRegion.CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
                    mergedRegion.CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
                }

            }
        }

    }
}
